package com.example.lets;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.github.ksoichiro.android.observablescrollview.CacheFragmentStatePagerAdapter;
import com.github.ksoichiro.android.observablescrollview.ObservableListView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.google.samples.apps.iosched.ui.widget.SlidingTabLayout;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.widget.CircleImageView;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.listener.FindListener;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class SearchActivity extends BaseActivity implements ObservableScrollViewCallbacks {

	private View mHeaderView;
	private View mToolbarView;
	private int mBaseTranslationY;
	private ViewPager mPager;
	private NavigationAdapter mPagerAdapter;

	public final static int ACTIVITY_PAGE = 0;
	public final static int USER_PAGE = 1;
	public final static int REFRESH = 2;

	public static EditText et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
		setTitle(null);

		mHeaderView = findViewById(R.id.header);
		ViewCompat.setElevation(mHeaderView, getResources().getDimension(R.dimen.toolbar_elevation));
		mToolbarView = findViewById(R.id.toolbar);
		mPagerAdapter = new NavigationAdapter(this, getSupportFragmentManager());
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mPagerAdapter);

		et = (EditText) findViewById(R.id.home_search_edittext);

		SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
		slidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
		slidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.accent));
		slidingTabLayout.setDistributeEvenly(true);
		slidingTabLayout.setViewPager(mPager);

		// When the page is selected, other fragments' scrollY should be adjusted
		// according to the toolbar status(shown/hidden)
		slidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int i, float v, int i2) {
			}

			@Override
			public void onPageSelected(int i) {
				//propagateToolbarState(toolbarIsShown());
				showToolbar();
			}

			@Override
			public void onPageScrollStateChanged(int i) {
			}
		});

		propagateToolbarState(toolbarIsShown());


		// original codes start here
		ImageButton search = (ImageButton)this.findViewById(R.id.home_search_button);
		search.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPagerAdapter = new NavigationAdapter(SearchActivity.this, getSupportFragmentManager());
				mPager.setAdapter(mPagerAdapter);
			}
		});


		Button back = (Button) this.findViewById(R.id.search_back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				SearchActivity.this.finish();
			}

		});
	}

	public static String ruleSearchString(String inputStr){
		StringBuffer newString = new StringBuffer();
		char temp;
		for(int i = 0; i < inputStr.length(); i++){
			temp = inputStr.charAt(i);
			if(temp == '[' || temp == '(' || temp == ')' || temp == '*' ||
					temp == '.' || temp == '\\' || temp == '?' || temp == '+' ||
					temp == '{' ){
				newString.append('\\');

			}
			newString.append(temp);
		}
		return new String (newString);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings)
			return true;
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
		if (dragging) {
			int toolbarHeight = mToolbarView.getHeight();
			float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
			if (firstScroll) {
				if (-toolbarHeight < currentHeaderTranslationY) {
					mBaseTranslationY = scrollY;
				}
			}
			float headerTranslationY = ScrollUtils.getFloat(-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
			ViewPropertyAnimator.animate(mHeaderView).cancel();
			ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
		}
	}

	@Override
	public void onDownMotionEvent() {
	}

	@Override
	public void onUpOrCancelMotionEvent(ScrollState scrollState) {
		mBaseTranslationY = 0;

		Fragment fragment = getCurrentFragment();
		if (fragment == null) {
			return;
		}
		View view = fragment.getView();
		if (view == null) {
			return;
		}

		int toolbarHeight = mToolbarView.getHeight();
		final ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
		if (listView == null) {
			return;
		}
		int scrollY = listView.getCurrentScrollY();
		if (scrollState == ScrollState.DOWN) {
			showToolbar();
		} else if (scrollState == ScrollState.UP) {
			if (toolbarHeight <= scrollY) {
				hideToolbar();
			} else {
				showToolbar();
			}
		} else {
			// Even if onScrollChanged occurs without scrollY changing, toolbar should be adjusted
			if (toolbarIsShown() || toolbarIsHidden()) {
				// Toolbar is completely moved, so just keep its state
				// and propagate it to other pages
				propagateToolbarState(toolbarIsShown());
			} else {
				// Toolbar is moving but doesn't know which to move:
				// you can change this to hideToolbar()
				showToolbar();
			}
		}
	}

	private Fragment getCurrentFragment() {
		return mPagerAdapter.getItemAt(mPager.getCurrentItem());
	}

	private void propagateToolbarState(boolean isShown) {
		int toolbarHeight = mToolbarView.getHeight();

		// Set scrollY for the fragments that are not created yet
		mPagerAdapter.setScrollY(isShown ? 0 : toolbarHeight);

		// Set scrollY for the active fragments
		for (int i = 0; i < mPagerAdapter.getCount(); i++) {
			// Skip current item
			/*if (i == mPager.getCurrentItem()) {
				continue;
			}*/

			// Skip destroyed or not created item
			Fragment f = mPagerAdapter.getItemAt(i);
			if (f == null) {
				continue;
			}

			View view = f.getView();
			if (view == null) {
				continue;
			}
			ObservableListView listView = (ObservableListView) view.findViewById(R.id.scroll);
			if (isShown) {
				// Scroll up
				if (0 < listView.getCurrentScrollY()) {
					listView.setSelection(0);
				}
			} else {
				// Scroll down (to hide padding)
				if (listView.getCurrentScrollY() < toolbarHeight) {
					listView.setSelection(1);
				}
			}
		}
	}

	private boolean toolbarIsShown() {
		return ViewHelper.getTranslationY(mHeaderView) == 0;
	}

	private boolean toolbarIsHidden() {
		return ViewHelper.getTranslationY(mHeaderView) == -mToolbarView.getHeight();
	}

	private void showToolbar() {
		float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
		if (headerTranslationY != 0) {
			ViewPropertyAnimator.animate(mHeaderView).cancel();
			ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
		}
		propagateToolbarState(true);
	}

	private void hideToolbar() {
		float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
		int toolbarHeight = mToolbarView.getHeight();
		if (headerTranslationY != -toolbarHeight) {
			ViewPropertyAnimator.animate(mHeaderView).cancel();
			ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
		}
		propagateToolbarState(false);
	}

	private static class NavigationAdapter extends CacheFragmentStatePagerAdapter {

		private static final String[] TITLES = new String[]{"活动", "用户"};
		private SearchActivity context;

		private int mScrollY;

		public NavigationAdapter(SearchActivity context, FragmentManager fm) {
			super(fm);
			this.context = context;
		}

		public void setScrollY(int scrollY) {
			mScrollY = scrollY;
		}

		@Override
		protected Fragment createItem(int position) {
			Log.i("search", "创建页面" + position);
			Bundle args = new Bundle();
			Fragment f;
			if (position == 0) {
				if (0 < mScrollY)
					args.putInt(ActivitySearchFragment.ARG_INITIAL_POSITION, 1);
				ActivitySearchFragment.context = this.context;
				f = new ActivitySearchFragment();
			} else {
				if (0 < mScrollY)
					args.putInt(UserSearchFragment.ARG_INITIAL_POSITION, 1);
				UserSearchFragment.context = this.context;
				f = new UserSearchFragment();
			}
			f.setArguments(args);
			return f;
		}

		@Override
		public int getCount() {
			return TITLES.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return TITLES[position];
		}
	}
}

class SearchAdapter extends BaseAdapter {

	private LayoutInflater mInflater; // ??????LayoutInfalter??????????????
	private ArrayList<HashMap<String, Object>> list; // ?????????????????锟斤拷?
	private Context context;

	public SearchAdapter(Context context, ArrayList<HashMap<String, Object>> list) {
		this.mInflater = LayoutInflater.from(context);
		this.list = list;
		this.context = context;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int i) {
		return list.get(i);
	}

	@Override
	public long getItemId(int i) {
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		final UserViewHolder holder;

		if (convertView == null) {

			convertView = mInflater.inflate(R.layout.listview_item_user, null);
			holder = new UserViewHolder();

			holder.image = (CircleImageView) convertView.findViewById(R.id.ItemImage);
			holder.name  = (TextView)        convertView.findViewById(R.id.ItemName);
			holder.tag1  = (TextView)        convertView.findViewById(R.id.ItemTag1);
			holder.tag2  = (TextView)        convertView.findViewById(R.id.ItemTag2);
			holder.tag3  = (TextView)        convertView.findViewById(R.id.ItemTag3);

			convertView.setTag(holder);
		}
		else{
			holder = (UserViewHolder) convertView.getTag();
		}

		holder.name.setText(list.get(position).get("ItemName").toString());
		holder.tag1.setText(list.get(position).get("ItemTag1").toString());
		holder.tag2.setText(list.get(position).get("ItemTag2").toString());
		holder.tag3.setText(list.get(position).get("ItemTag3").toString());

		String fileName = (String) list.get(position).get("ItemPicFileName");

		String cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + fileName;
		String[] name = fileName.split("\\.");
		String newFileName = name[0] + "_1_200_0_100." + name[1];
		String cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;

		if ((new File(cacheDownloadPath)).exists()) { // ?????????????

			if ((new File(cacheThumbnailPath)).exists()) { // ?????????????

				Log.i("bmob", "?????????锟斤拷" + cacheThumbnailPath);
				Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
				holder.image.setImageBitmap(bm);

			} else { // ????????锟斤拷?????????????????????

				BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 1, new LocalThumbnailListener() {

					@Override
					public void onSuccess(String thumbnailPath) {
						Log.i("bmob", "localThumbnail-->???????????锟斤拷?? :" + thumbnailPath);
						Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
						holder.image.setImageBitmap(bm);
					}

					@Override
					public void onError(int statuscode, String errormsg) {
						Log.i("bmob", "localThumbnail-->???????????? :" + statuscode + "," + errormsg);
					}
				});

			}

		} else { // ???锟斤拷????????????????

			BTPFileResponse response = BmobProFile.getInstance(context).download(fileName, new DownloadListener() {

				@Override
				public void onSuccess(String fullPath) {
					Log.i("bmob", "????????" + fullPath);
					// ?????????????????????????
					BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 1, new LocalThumbnailListener() {

						@Override
						public void onSuccess(String thumbnailPath) {
							Log.i("bmob", "localThumbnail-->???????????锟斤拷?? :" + thumbnailPath);
							Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
							holder.image.setImageBitmap(bm);
						}

						@Override
						public void onError(int statuscode, String errormsg) {
							Log.i("bmob", "localThumbnail-->???????????? :" + statuscode + "," + errormsg);
						}
					});
					String str = BmobPro.getInstance(context).getCacheDownloadDir();
					Log.i("bmob", str);
				}

				@Override
				public void onProgress(String localPath, int percent) {
					Log.i("bmob", "download-->onProgress :" + percent);
				}

				@Override
				public void onError(int statuscode, String errormsg) {
					Log.i("bmob", "???????" + statuscode + "--" + errormsg);
					//Toast.makeText(context, "???????"+ statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
				}
			});
		}
		return convertView;
	}
}

class UserViewHolder {
	public CircleImageView image;
	public TextView name;
	public TextView tag1;
	public TextView tag2;
	public TextView tag3;
}